package svc

import (
	"log"

	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/rest"
	"ruikc.com/server/api/internal/config"
	"ruikc.com/server/api/internal/middleware"
	"xorm.io/xorm"
)

type ServiceContext struct {
	Config         config.Config
	Rds            *redis.Redis
	Db             *xorm.Engine
	UserMiddleware rest.Middleware
}

func NewServiceContext(c config.Config) *ServiceContext {
	rds, err := redis.NewRedis(redis.RedisConf{
		Host: c.RedisConfig.Host,
		Type: c.RedisConfig.Type,
		Pass: c.RedisConfig.Pass,
	})
	if err != nil {
		log.Panic("redis error :", err)
	}
	engine, err := xorm.NewEngine("mysql", c.DataSource)
	if err != nil {
		log.Panic("mysql connection :", err)
	}
	engine.ShowSQL(true)
	err = engine.Ping()
	if err != nil {
		log.Panic("mysql error :", err)
	}
	return &ServiceContext{
		Config:         c,
		Rds:            rds,
		Db:             engine,
		UserMiddleware: middleware.NewUserMiddleware(c).Handle,
	}
}
